package com.wizz.trade.auth.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wizz.trade.auth.mapper.SysMenuMapper;
import com.wizz.trade.auth.service.SysUserService;
import com.wizz.trade.common.LoginUser;
import com.wizz.trade.common.ServiceException;
import com.wizz.trade.auth.entity.SysUser;
import com.wizz.trade.auth.mapper.SysUserMapper;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;

/**
 * @author fyftless
 * <p>
 * Security 框架中的 UserDetailsService 接口，用于获取用户信息
 */
@Service
public class UserDetailServiceImpl implements UserDetailsService {

    @Resource
    private SysUserMapper sysUserMapper;

    @Resource
    private SysMenuMapper sysMenuMapper;


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {


        //根据用户名查询用户信息
        LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysUser::getUserName, username);

        SysUser user = sysUserMapper.selectOne(wrapper);
        //如果查询不到数据就通过抛出异常来给出提示
        if (Objects.isNull(user)) {
            throw new ServiceException("用户名或密码错误");
        }
        List<String> permissions = sysMenuMapper.getMenusByUserId(user.getId());
        //封装成UserDetails对象返回
        return new LoginUser(user, permissions);
    }
}
